var socket = {}
var socket_io = require('socket.io');
let sqlQuery = require("../mysql/mysql");
// socket.io封装
function getSocket(server){
 var io = require('socket.io')(server);
  // var io = socket_io.listen(server);//监听传入的server
  
    // 1.connection监听单个连接.
  io.on('connection',function(socket){
    console.log("我来了，宝贝");
    console.log("id为"+socket.id+"成功建立连接！");
    io.emit('this', { will: 'be received by everyone'});
  /****************************************************************************** */  
    //1.3监听进入主页
    socket.on('enter_home',async(data)=>{
      console.log(data)
      let users;
      if(data.users!="管理员"){
        users = data.users.slice(1,-1);
      }else{users = data.users}
      //最新未接收的消息
      let sqlStr2 = 'select * from onepice_chat where isread = ? and to_user=?'
      let result2 = await sqlQuery(sqlStr2,['false',users]);
      console.log("***************用户进入home后的未读信息状态*************")
      console.log(Array.from(result2))
      console.log("***************用户进入home后的未读信息状态*************")
      socket.emit('unreadMsg',Array.from(result2));//未读消息发送
    })

    //1.4监听进入聊天,触发unread函数,发送用户列表，发送未读信息的数据
    socket.on('enter_chat',async(data)=>{
      console.log(data)
      let users;
      if(data.users!="管理员"){
        users = data.users.slice(1,-1);
      }else{users = data.users}
      //发送用户列表消息
      let sqlStr = "select * from onepice_user";
      let result_user = await sqlQuery(sqlStr);
      io.sockets.emit('totalUsers',Array.from(result_user))
      //最新未接收的消息
      let sqlStr2 = 'select * from onepice_chat where isread = ? and to_user=?'
      let result2 = await sqlQuery(sqlStr2,['false',users]);
      // console.log(Array.from(result2))
      socket.emit('unreadMsg',Array.from(result2));//未读消息发送
    })
/****************************************************************************** */
    //1.5监听已读，已读则把已读标签设置为true
      socket.on("hasRead",async(data)=>{
        console.log("has read****************")
        console.log(data)
        console.log("has read****************");
        let from_user;
        let to_user;
        if(data.from_user!='管理员'){
          from_user = data.from_user
          to_user = data.to_user;
        }else{  
        from_user = data.from_user;
        to_user = data.to_user
        }
        console.log("未读信息来自："+from_user)
        console.log("接收对象："+to_user);
        console.log("消息内容："+data.contentWord);
        let sqlStr;
        let arr = ['true',from_user,to_user]
        let result=[];
        
        sqlStr = "update onepice_chat set isread=? where from_user = ? and to_user=?";
        result = setTimeout( async() => {
        return await sqlQuery(sqlStr,arr)
        }, 500);
       console.log("未读更新状态******************")
        console.log(result)
       console.log("未读更新状态******************")
      })
   
    
//****************************************************************************** */
    //1.1监听登录事件,登录则修改登录状态为true：该方法在chat.vue模块中定义发送
    socket.on('login',async(data)=>{
      let users;
      if(data.users!="管理员"){
        users = data.users.slice(1,-1);
      }else{users = data.users}
      let id = data.id;
      //修改数据库登录信息
      let sqlStr = "update onepice_user set socketid=?, isonline=? where users = ? and id = ?"
      // update onepice_user u set u.socketid='kkk', u.isonline='true' where u.users = '杰克'
      let arr = [socket.id,"true",users,id]
      let result = await sqlQuery(sqlStr,arr);
      console.log("登录触发，sockid="+socket.id)
      console.log("登录触发，id="+id)
      console.log(data)
    })
    // 1.2.监听断开
    socket.on('disconnect',async(reason)=>{
      console.log("id为"+socket.id+"的用户端口断开……断开原因："+reason);
      //断开就修改登录信息
      let sqlStr = "update onepice_user set socketid=?, isonline=? where socketid = ?"
      let arr = [null,null,socket.id]
      let result = await sqlQuery(sqlStr,arr);
      console.log("断开后，用户修改状态***************")  
      console.log(result)
      console.log("断开后，用户修改状态***************")  
    })
 /****************************************************************************** */   

    //1.6监听客户端发送的信息,监听用户上线，如果在线直接利用onlineChat封装数据，发送给前端
    socket.on('client',async function(data){
     
      let users;
      if(data.to_user!="管理员"){
        users =data.to_user;
      }else{users = data.to_user}
      console.log("*******测试users")
      console.log(users)
      console.log("*******测试users")
      let sqlStr2 = "select * from onepice_user where users =? and isonline= ?"
      let result2 = await sqlQuery(sqlStr2,[users,'true'])
      console.log("*******测试socket.id")
      console.log(result2)
      console.log("*******测试socket.id")
      //发送数据库个人信息给前台.
      // 判断查询结果长度是否大于0，大于0，则在线
      if(result2.length>0){
        let socketId = result2[0].socketid;
        console.log("*******************************")
      console.log(result2[0].users)
      console.log("接收者"+users+"的id:"+result2[0].socketid)
      console.log(data.from_user+"发给："+users)
      console.log("id?="+socketId)
      console.log("*********************************")
        // 如果在线，直接发信息
        
        //聊天数据通过onlineChat，发送给前端,只会发给对应的socketId的用户，即to_user
        socket.to(socketId).emit("onlineChat",data);
        console.log(data.from_user+":聊天信息："+data.contentWord)
        //将聊天内容放到数据库
        let strSql3 = 'insert into onepice_chat (from_user,to_user,contentWord,time,isread) values (?,?,?,?,?)';
        let arr3 = [data.from_user,data.to_user,data.contentWord,data.time,'true'];//因为用户在线直接设置已读
        let result3 =  sqlQuery(strSql3,arr3)
      }else{
         //不在线就直接将聊天内容放到数据库,此处兼容操作，因为管理员与普通用户不在一张表
        // socket.to(socketId).emit("onlineChat",data);
        // console.log(data.users+":聊天信息："+data.contentWord)
         let strSql3 = 'insert into onepice_chat (from_user,to_user,contentWord,time,isread) values (?,?,?,?,?)';
         let arr3 = [data.from_user,data.to_user,data.contentWord,data.time,'false'];//因为用户在线直接设置已读
         let result3 = sqlQuery(strSql3,arr3)
      }
      
      // console.log("hmy 666!");
      console.log(data);
      // console.log(data.users.slice(1,-1)==' 杰克')
      // console.log(result) 
    })
  });
 
  console.log(io)
}
/****************************************************************************** */



socket.getSocket = getSocket;
//导出socket
module.exports = socket

// 1、不存在 room 的：
// io.emit() // 广播到所有的 socket client，等于 io.sockets.emit()
// socket.emit() // 广播到当前连接的 socket client
// socket.broadcast.emit() // 广播到 除当前连接的 socket client 之外的其他 socket client
// 2、存在 room 的：
// socket.broadcast.to(roomId).emit()
